/**
 * 将旧系统的素材数据同步到新系统
 */

import * as fs from "fs";
import * as path from "path";
import * as os from "os";

import dayjs from "dayjs";

import config from "./config";
import { downFile, uploadFile, getMaterialDurationAndType } from "./util";

import { materialSave, materialPage } from "./api/newApi";

import { getMaterialPage } from "./api/oldApi";

const __dirname = path.resolve();

const DIR_PATH = path.resolve(__dirname, "./downloadMaterials");
const SKIP_FILE_NAME_PATH = path.resolve(DIR_PATH, "./skipFileName");
const queryParams: Parameters<typeof getMaterialPage>[0] = {};

let currentMaterial: any;

(async () => {
	if (!fs.existsSync(DIR_PATH)) fs.mkdirSync(DIR_PATH);
	try {
		main();
	} catch (err) {
		console.log("err: ", err instanceof Error ? err.message : err);
	}
})();

async function main() {
	try {
		const allMaterials = await getMaterialPage(queryParams).then((res) => res.data.data);
		if (allMaterials.length === 0) {
			console.log("素材全部迁移完毕");
			process.exit(1);
		}

		for (let i = 0; i < allMaterials.length; i++) {
			currentMaterial = allMaterials[i];
			const materialList = await materialPage(currentMaterial.fileName).then((res) => res.data?.data?.records || []);

			if (materialList.length === 0) {
				const materialsAbsolute = path.resolve(DIR_PATH, currentMaterial.fileName);
				const downUrl = config.OLD.DOWNLOAD_URL + currentMaterial.fileSource;

				if (fs.existsSync(SKIP_FILE_NAME_PATH)) {
					const content = await fs.promises.readFile(SKIP_FILE_NAME_PATH);
					const skipFileName = content.toString()?.split(os.EOL)?.filter(Boolean);
	
					if (skipFileName.includes(currentMaterial.fileName)) {
						console.log(`跳过【${currentMaterial.fileName}】`);
						continue;
					}
				}

				if (!fs.existsSync(materialsAbsolute)) {
					console.log(`开始下载【${currentMaterial.fileName}】`);
					await downFile(downUrl, materialsAbsolute);
				}

				console.log(`开始上传【${currentMaterial.fileName}】`);
				const fileUrl = await uploadFile(materialsAbsolute);
				const { duration, type, $fileType } = await getMaterialDurationAndType(materialsAbsolute);
				const stat = fs.statSync(materialsAbsolute);
				const remarks = dayjs().format("YYYY-MM-DD HH:mm:ss") + " 迁移上传";

				const uploadData = {
					duration,
					type,
					file: fileUrl,
					name: currentMaterial.fileName,
					resolution: currentMaterial.fileResolution,
					size: stat.size,
					officeCode: currentMaterial.officeId,
					officeName: currentMaterial.officeName,
					status: "0",
					isShim: "2",
					isUnAudit: "1",
					remarks
				};
				console.log(`开始上传【${currentMaterial.fileName}】`);
				await materialSave(uploadData);
				console.log(`【${currentMaterial.fileName}】上传成功`);
				console.log(`删除【${currentMaterial.fileName}】:${materialsAbsolute}`);
				await fs.promises.rm(materialsAbsolute);
			} else {
				console.log(`【${currentMaterial.fileName}】素材数据已存在`);
				// await materialSave({
				// 	...materialList[0],
				// 	officeCode: currentMaterial.officeId,
				// 	officeName: currentMaterial.officeName,
				// });
				// console.log(`【${currentMaterial.fileName}】素材数据已更新`);
			}
		}
		console.log("success");
	} catch (err) {
		console.log("err: ", err instanceof Error ? err.message : err);
		console.log(`素材迁移失败: ${currentMaterial.fileName}`);

		// 记录失败的继续上传
		fs.appendFileSync(SKIP_FILE_NAME_PATH, `${currentMaterial.fileName}${os.EOL}`);
		console.log("========== 继续迁移 ==========");
		main();
	}
}
